﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

public partial class ViewClient : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

    List<_Company_bank> Client_bank = new List<_Company_bank>();
    List<_Adress> Client_address = new List<_Adress>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated == false)
        {
            Response.Redirect("login.aspx");
        }

        if (Request.IsAuthenticated)
        {
            string n = "";
            SqlCommand sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            conn.Open();
            SqlDataReader dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            conn.Close();

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData();
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }
    }

    public void SetData()
    {
        Response.Write(lbl_company_id.Text = Session["Company_ID"].ToString());

        lblName.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_name;
        lblRegnr.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_reg_nr;
        lblVat.Text = _User_company.Sel_User_company(lbl_company_id.Text)._company_vat;
        lblPosition.Text = _User_company.Sel_User_company(lbl_company_id.Text)._position;

        Response.Clear();

        string company_id = lbl_company_id.Text;

        Client_bank = _Company_bank.Select_Company_bank(company_id);
        Bank_list.DataSource = Client_bank;
        Bank_list.DataBind();

        conn.Open();
        SqlCommand selCmd2 = new SqlCommand("SELECT id, bank_name FROM bank", conn);
        SqlDataReader rdd = selCmd2.ExecuteReader();
        while (rdd.Read())
        {
            ListItem item = new ListItem();
            item.Value = rdd["id"].ToString();
            item.Text = rdd["bank_name"].ToString();
            Drop_bank.Items.Add(item);
        }
        Drop_bank.Items.Insert(0, "--Select--");
        rdd.Close();
        conn.Close();

        Client_address = _Adress.Select_Company_address(company_id);
        Address_list.DataSource = Client_address;
        Address_list.DataBind();
    }
    private string Sort
    {
        get
        {
            return String.Concat(this.SortExpression, (this.SortDirection == SortDirection.Ascending) ? " DESC" : " ASC");
        }
    }
    private SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Descending;
            }

            return (SortDirection)ViewState["SortDirection"];
        }
        set { ViewState["SortDirection"] = value; }
    }
    private string SortExpression
    {
        get
        {
            if (ViewState["SortExpression"] == null)
            {
                ViewState["SortExpression"] = "ID";
            }

            return ViewState["SortExpression"].ToString();
        }
        set { ViewState["SortExpression"] = value; }
    }

    protected void Bank_list_Sorting(object sender, ListViewSortEventArgs e)
    {
        if (this.SortExpression.Equals(e.SortExpression))
        {
            this.SortDirection = (this.SortDirection == SortDirection.Descending)
                  ? SortDirection.Ascending
                  : SortDirection.Descending;
        }
        else
        {
            this.SortDirection = SortDirection.Descending;
        }
        this.SortExpression = e.SortExpression;
        this.SetData();
    }
    protected void Bank_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        //if (e.CommandName == "Update_bank")
        //{
        //    //Tabula Company_bank
        //    var company_bank_ID = e.Item.FindControl("id_company_bankLabel") as Label;
        //    var company_ID = e.Item.FindControl("id_companyLabel") as Label;
        //    var bank_ID = e.Item.FindControl("id_bankLabel") as Label;

        //    //Tabula Bank
        //    var id_bank = e.Item.FindControl("id_bankLabel") as Label;
        //    var bank_name = e.Item.FindControl("tb_bank") as TextBox;
        //    var bank_swift = e.Item.FindControl("tb_bank_swift") as TextBox;

        //    _Company_bank.Update(id_bank.Text, bank_name.Text, bank_swift.Text);

        //    Response.Redirect("ViewCompany.aspx");
        //}
        //if (e.CommandName == "Cancel_bank")
        //{
        //    Response.Redirect("ViewClient.aspx");
        //}
        //if (e.CommandName == "Insert_bank")
        //{
        //    string id_company = lbl_company_id.Text;
        //    var bank_name = e.Item.FindControl("tb_bank_name_insert") as TextBox;
        //    var bank_swift = e.Item.FindControl("tb_bank_swift_insert") as TextBox;

        //    //_Company_bank.Insert(bank_name.Text, bank_swift.Text);

        //    //Atlasam pēdējo ievadīto bankas ID un padodam tālāk
        //    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
        //    SqlCommand SelMaxBankID = new SqlCommand("SELECT MAX(id) FROM bank", conn);
        //    conn.Open();
        //    string bank_id = Convert.ToString(SelMaxBankID.ExecuteScalar());
        //    conn.Close();

        //    _Company_bank.Insert_company_bank(id_company, bank_id);

        //    Response.Redirect("ViewCompany.aspx");
        //}

        if (e.CommandName == "Edit")
        {
            lbl_edit.Text = "true";
            tb_account.Text = "";
            bt_ok_bank.Text = "Edit";

            var company_bank_ID = e.Item.FindControl("id_company_bankLabel") as Label;
            lbl_company_bankID.Text = company_bank_ID.Text;
            var company_ID = e.Item.FindControl("id_companyLabel") as Label;
            lbl_companyID.Text = company_ID.Text;
            var bank_ID = e.Item.FindControl("id_bankLabel") as Label;
            var account_ID = e.Item.FindControl("id_accountLabel") as Label;
            lbl_accountID.Text = account_ID.Text;

            int id_bank = Convert.ToInt32(bank_ID.Text);
            int id_account = Convert.ToInt32(account_ID.Text);

            SqlCommand SelBank = new SqlCommand("SELECT id, bank_name FROM bank WHERE id=@bank_id", conn);
            SelBank.Parameters.Add(new SqlParameter("@bank_id", System.Data.SqlDbType.Int)).Value = id_bank;
            conn.Open();
            SqlDataReader dr = SelBank.ExecuteReader();
            while (dr.Read())
            {
                ListItem item = new ListItem();
                item.Value = dr["id"].ToString();
                item.Text = dr["bank_name"].ToString();
                Drop_bank.Items.Insert(0, item);
                Drop_bank.SelectedIndex = -1;
            }
            dr.Close();
            conn.Close();

            SqlCommand SelAccount = new SqlCommand("SELECT account_number FROM account_number WHERE id_account_number=@account_id", conn);
            SelAccount.Parameters.Add(new SqlParameter("@account_id", System.Data.SqlDbType.Int)).Value = id_account;
            conn.Open();
            SqlDataReader dr2 = SelAccount.ExecuteReader();
            while (dr2.Read())
            {
                tb_account.Text = dr2["account_number"].ToString();
            }
            dr2.Close();
            conn.Close();
        }

        if (e.CommandName == "Delete")
        {
            var company_bank_ID = e.Item.FindControl("id_company_bankLabel") as Label;
            //_Account.Delete(company_bank_ID.Text);
            _Company_bank.Delete(company_bank_ID.Text);
            Response.Redirect("ViewClient.aspx");
        }
    }
    protected void Bank_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("bankID").Visible = false;
        e.Item.FindControl("company_bankID").Visible = false;
        e.Item.FindControl("companyID").Visible = false;
        e.Item.FindControl("accountID").Visible = false;
    }
    protected void Bank_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    //protected void Bank_list_ItemEditing(object sender, ListViewEditEventArgs e)
    //{
    //    Bank_list.EditIndex = e.NewEditIndex;
    //    SetData();
    //}
    protected void bt_ok_bank_Click(object sender, EventArgs e)
    {
        string id_company = lbl_company_id.Text;
        string bank_id = Drop_bank.SelectedItem.Value;
        if (lbl_edit.Text == "false")
        {
            _Company_bank.Insert(id_company, bank_id,tb_account.Text);

            SqlCommand SelMaxBankID = new SqlCommand("SELECT MAX(id) FROM company_bank", conn);
            conn.Open();
            string company_bank_id = Convert.ToString(SelMaxBankID.ExecuteScalar());
            conn.Close();

            string number = tb_account.Text;

        }
        else
        {
            _Company_bank.Update(lbl_company_bankID.Text, lbl_companyID.Text, Drop_bank.SelectedItem.Value, lbl_accountID.Text, tb_account.Text);
            Response.Redirect("ViewClient.aspx");
        }
    }

    protected void Address_list_Sorting(object sender, ListViewSortEventArgs e)
    {
        if (this.SortExpression.Equals(e.SortExpression))
        {
            this.SortDirection = (this.SortDirection == SortDirection.Descending)
                  ? SortDirection.Ascending
                  : SortDirection.Descending;
        }
        else
        {
            this.SortDirection = SortDirection.Descending;
        }
        this.SortExpression = e.SortExpression;
        this.SetData();
    }
    protected void Address_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        //if (e.CommandName == "Update_address")
        //{
        //    var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
        //    var company_ID = e.Item.FindControl("id_companyLabel") as Label;
        //    var address = e.Item.FindControl("tb_address") as TextBox;

        //    _Adress.Update(addres_ID.Text, company_ID.Text, address.Text);

        //    Response.Redirect("ViewClient.aspx");
        //}
        if(e.CommandName=="Edit")
        {
            lbl_edit_address.Text = "true";
            tb_address.Text = " ";
            bt_ok_address.Text = "Edit";

            var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
            int address_id = Convert.ToInt32(addres_ID.Text);
            lbl_address_id.Text = addres_ID.Text;
            int client_id = Convert.ToInt32(lbl_company_id.Text);

            SqlCommand sCmd_address = new SqlCommand("SELECT address FROM company_address WHERE id=@address_id AND id_company=@company_id", conn);
            sCmd_address.Parameters.Add(new SqlParameter("@address_id", SqlDbType.Int)).Value = address_id;
            sCmd_address.Parameters.Add(new SqlParameter("@company_id", SqlDbType.Int)).Value = client_id;
            conn.Open();
            SqlDataReader dr = sCmd_address.ExecuteReader();
            while (dr.Read())
            {
                tb_address.Text = dr["address"].ToString();
            }
            dr.Close();
            conn.Close();
        }

        if (e.CommandName == "Cancel_address")
        {
            Response.Redirect("ViewClient.aspx");
        }
        //if (e.CommandName == "Insert_address")
        //{
        //    string id_company = lbl_company_id.Text;
        //    var address = e.Item.FindControl("tb_address_insert") as TextBox;

        //    _Adress.Insert(id_company, address.Text);
        //    Response.Redirect("ViewClient.aspx");
        //}
        if (e.CommandName == "Delete")
        {
            var addres_ID = e.Item.FindControl("id_addressLabel") as Label;
            _Adress.Delete(addres_ID.Text);
            Response.Redirect("ViewClient.aspx");
        }
    }
    protected void Address_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("addressID").Visible = false;
        e.Item.FindControl("companyID").Visible = false;
    }
    protected void Address_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        
    }
    //protected void Address_list_ItemEditing(object sender, ListViewEditEventArgs e)
    //{
    //    Address_list.EditIndex = e.NewEditIndex;
    //    SetData();
    //}
    protected void bt_ok_address_Click(object sender, EventArgs e)
    {
        string id_company = lbl_company_id.Text;
        string id_address = lbl_address_id.Text;

        if (lbl_edit_address.Text == "false")
        {
            _Adress.Insert(id_company,tb_address.Text);

            Response.Redirect("ViewClient.aspx");
        }
        else
        {
            _Adress.Update(id_address, id_company, tb_address.Text);
            Response.Redirect("ViewClient.aspx");
        }
    }
}